import {
	getClientUserInfo
} from "@/common/api/index_api.js"
import {
	getUserInfoByCode,
	getUserDiscountInfo,
	getUserDiscountTakeEffect, isUserMember
} from '@/common/api/user_api.js'
import {
	removeEmptyProperty
} from '@/common/utils/util.js'

import {
	userInfoStorage
} from '@/common/utils/config.js'
import {
	ceping_data_list,
	isEshopScl
} from '@/common/api/scl_api.js'

import dayjs from 'dayjs'

export default {
	namespaced: true,
	state: () => ({
		userInfo: {
			userId: '',
			openId: '',
			nickName: '',
			sex: '',
			avatar: '',
			phone: '',
			roles: [],
			username: '',
			clientUserUid: '',

		} || uni.getStorageSync('userInfoStorage'),
		inviterId: '',
		currentGuestId: '',
		roles: [],
		currentGroup: 'A', // 用来判断展示的样式，及拉取的数据
		initGroup: '', // 用来判断是否跳转去做初始测评
		isVip: false,
		discountList: {},
		discountNum: null,
		discountTime: '',
		discountType: 1, // 优惠券类型 1/2/3/4  折扣/满减/立减/兑换
		discountId: '',
		discountValidNumber: 0,
		purchaseAndUsageCount: 0, //购买了且做了测评的次数；
		couponModalTime: uni.getStorageSync('couponModalTime') || '1998-03-25 13:00:00',
		couponFirstMonthTime: '',
		firstSclIsEshop: false,
		couponModalTimeD: uni.getStorageSync('couponModalTimeD') || '1998-03-25 13:00:00',
		isOldUser: false,
		newUserCouponModalShow: false,
		adType: null,
		countdownHandlId: '', //延迟执行的事件id 
		userChannel: '', //身份渠道 如：电商
		userJson: '',
		isShowEconsultBlock: false,
		isShowEconsultModal: false,
		isPaySclExamination: false, // 是否购买过心理体检测评包
		notUseLbYiyuan: false,
		actCouponCode: '',
		actCouponId: '',
		// 2025年新增加的会员功能
		member: {
			// 0/1/2 不是会员/过期/是会员
			userMemberStatus: 0,
			// 会员结束时间
			memberEndTime: '',
			memberEndTimeStr: ''
		}
	}),
	mutations: {
		setIsShowEconsultBlock(state, data) {
			state.isShowEconsultBlock = data
		},
		setIsShowEconsultModal(state, data) {
			state.isShowEconsultModal = data
		},
		setCountdownHandlId(state, data) {
			state.countdownHandlId = data
		},
		setUserJson(state, data) {
			console.log(data, '------data--setUserJson---')
			state.userJson = data
			state.userInfo.userJson = data

			uni.setStorageSync(userInfoStorage, state.userInfo)
		},
		setAdType(state, data) {
			state.adType = data
		},
		setFirstSclIsEshop(state, data) {
			state.firstSclIsEshop = data
		},
		setNewUserCouponModalShow(state, data) {
			state.newUserCouponModalShow = data
		},
		setNotUseLbYiyuan(state, data) {
			console.log('================setNotUseLbYiyuan==============', data)
			state.notUseLbYiyuan = data
		},
		setUserChannel(state, data) {
			state.userChannel = data
		},
		setCouponFirstMonthTime(state, data) {
			console.log(data, '--- setCouponFirstMonthTime')
			state.couponFirstMonthTime = data || 0
		},
		setCouponModalTime(state, data) {
			state.couponModalTime = data || '1998-03-25 13:00:00',
				uni.setStorageSync('couponModalTime', data)
		},
		setActCouponCode(state, data) {
			state.actCouponCode = data
		},
		setActCouponId(state, data) {
			state.actCouponId = data
		},
		setCouponModalTimeD(state, data) {
			state.couponModalTimeD = data || '1998-03-25 13:00:00',
				uni.setStorageSync('couponModalTimeD', data)
		},
		setDiscountNum(state, data) {
			state.discountNum = data
		},
		setDiscountType(state, data) {
			state.discountType = data
		},
		setDiscountTime(state, data) {
			state.discountTime = data
		},
		setDiscountId(state, data) {
			console.log(data, '-----setDiscountId')
			state.discountId = data
		},
		setDiscountValidNumber(state, data) {
			state.discountValidNumber = data
		},
		setCurrentGuestId(state, data) {
			state.currentGuestId = data
		},
		setPurchaseAndUsageCount(state, data) {
			state.purchaseAndUsageCount = data
		},
		setCurrentGroup(state, data) {
			console.log('data======', data)
			state.initGroup = 'A' //data
			state.currentGroup = 'A' //data || 'A' 
			// 应对版本需求 只生效A组，其他分组待产品通知后更改
		},
		setInviterId(state, data) {
			state.inviterId = data
		},
		setUserInfo(state, data) {
			console.log(data, '==========data====setUserInfo')
			state.userInfo = data;
			state.userInfo.userId = data.clientUserUid; //兼容之前的取参
			state.userJson = data.userJson
			uni.setStorageSync(userInfoStorage, data)
			// const userInfoObj = Object.assign({}, state.userInfo)

			// userInfoObj['userId'] = data.userId
			// userInfoObj['openId'] = data.openId
			// userInfoObj['nickName'] = data.nickName
			// userInfoObj['sex'] = data.sex
			// userInfoObj['avatar'] = data.avatar
			// userInfoObj['phone'] = data.phone
			// userInfoObj['roles'] = data.roles
			// userInfoObj['username'] = data.username

			// state.userInfo = {
			// 	...state.userInfo,
			// 	...removeEmptyProperty(userInfoObj)
			// }
		},

		setRoles(state, data) {
			state.roles = data;
		},
		setIsVip(state, data) {
			state.isVip = data
		},
		setDiscountList(state, data) {
			state.discountList = data
		},
		setIsOldUser(state, data) {
			state.isOldUser = data
		},
		setIsPaySclExamination(state, data) {
			state.isPaySclExamination = data
		},
		setMember(state, data) {
			state.member = data
		}
	},
	getters: {
		hasShowRecommendCheckupModal(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return obj.hasShowRecommendCheckupModal
				} catch (e) {
					return false
				}
			} else {
				return false
			}
		},
		hasSexualorientationAnswer(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return obj.sclSexualOrientationAnswer?.length >= 5
				} catch (e) {
					return false
				}
			} else {
				return false
			}
		},
		canSeeCheckupDepressedIntro(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return !obj.canSeeCheckupDepressedIntro
				} catch (e) {
					return true
				}
			} else {
				return true
			}
		},
		canSeeCheckupSexualityIntro(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return !obj.canSeeCheckupSexualityIntro
				} catch (e) {
					return true
				}
			} else {
				return true
			}
		},
		canSeeCheckupIntro(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return !obj.canSeeCheckupIntro

					// Y 弹出过，N 或null 未购买过
				} catch (e) {
					return true
				}
			} else {
				return true
			}
		},
		canBuyPayBackMBTI(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return !obj.canBuyPayBackMBTI
					// Y 弹出过，N 或null 未购买过
				} catch (e) {
					return true
				}
			} else {
				return true
			}
		},
		liveSclId(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return obj.sclId
					// Y 弹出过，N 或null 未购买过
				} catch (e) {
					return ''
				}
			} else {
				return ''
			}
		},
		canBuyPayBackSPM(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return !obj.canBuyPayBackSPM
					// Y 弹出过，N 或null 未购买过
				} catch (e) {
					return true
				}
			} else {
				return true
			}
		},
		canBuyPayBackLoveMBTI(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return !obj.canBuyPayBackLoveMBTI
					// Y 弹出过，N 或null 未购买过
				} catch (e) {
					return true
				}
			} else {
				return true
			}
		},
		hasShowYiyuanModal(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return obj.hasShowYiyuanModal == 'Y'
					// Y 弹出过，N 或null 未弹出过
				} catch (e) {
					return false
				}
			} else {
				return false
			}
		},
		hasCheckupTipEnd(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return obj.hasCheckupTipEnd == 'Y'
					// Y 弹出过，N 或null 未弹出过
				} catch (e) {
					return false
				}
			} else {
				return false
			}
		},
		hasShowTaskNotice(state) {
			if (state.userJson) {
				try {
					const obj = JSON.parse(state.userJson)
					return obj.hasShowTaskNotice == 'Y' || obj.hasShowTaskNotice == null

				} catch (e) {
					return true
				}
			} else {
				return true
			}
		},
		getUserInfo(state) {
			return state.userInfo
		},
		userId(state) {
			return state.userInfo?.userUid
		},
		clientUserUid(state) {
			return state.userInfo?.clientUserUid
		},
		adType(state) {
			return state.userInfo?.adType||''
		},
		avatar(state) {
			return state.userInfo?.avatar
		},
		uGender(state) {
			// 性别(字典 0未知 1男 2女)
			return state.userInfo?.sex
		},
		nickName(state) {
			return state.userInfo?.nickName
		},
		isEshopUser(state) {
			return state.userChannel == 'eshop'
		},
		isStaff(state) {
			return !!state.roles?.find(item => item.roleCode == 'store_advisor')
		},
		isOperation(state) {
			return !!state.roles.find(item => item.roleCode == 'storeServiceStaff' || item.roleCode == 'store_service_leader')
		},
		isLogin(state) { //只有已绑定手机号的用户才算正式登录
			// return !!state.userInfo//?.phone 
			return !!state.userInfo?.clientUserUid
		},
		hasPhone(state) {
			return !!state.userInfo?.phone
		},
		isInvite(state) {
			return !!state.inviterId
		},
		sysUserName(state) {
			return state.userInfo?.sysUserName
		},
		discountA(state) {
			//如果首单不是电商商品，则直接视为已领取
			if (state.firstSclIsEshop) {
				// return state.discountList?.A || false
				return state.discountList.ESHOP || false
			} else {
				return {
					id: state.discountList?.A?.id,
					isBool: true,
					validNumber: state.discountList?.A?.validNumber
				}
			}
		},
		discountB(state) {
			return state.discountList?.B || false
		},
		discountC(state) {
			return state.discountList?.C || false
		},
		discountD(state) {
			return state.discountList?.D || false
		},
		discountE(state) {
			return state.discountList?.E || false
		},
		discountNewUser400(state) {
			return state.discountList?.newUser400 || false
		},
		discountNewUser10(state) {
			return state.discountList?.newUser10 || false
		},
		discountOfficalAccount(state) {
			return state.discountList?.officalAccount || false
		},
		discountYiYuan(state) {
			return state.discountList?.yiyuan || false
		},
		usedOk(state) {
			return state.discountList?.usedOk || false
		}
	},
	actions: {
		async checkFirstSclIsEshop({
			state,
			commit
		}) {
			let result = true
			const {
				data: dRes
			} = await ceping_data_list({
				pageNo: 1
			})
			console.log(dRes, '====checkFirstSclIsEshop')
			if (dRes.success) {
				if (dRes.data.totalRows && dRes.data.totalRows > 0) {
					const {
						data: fRes
					} = await isEshopScl({
						sclId: dRes.data.rows[0].sclId
					})
					if (fRes.success) {
						console.log(fRes.data, '-----checkFirstSclIsEshop')
						result = fRes.data
						commit('setFirstSclIsEshop', fRes.data)
					}
				}
			}

			return result
		},
		checkUserIsLogin({
			state
		}) {
			if (!state.userInfo.clientUserUid) {
				//该用户不存在，前往登录页面
				uni.redirectTo({
					url: '/subcontractorA/authorization/authorization'
				})
				return false
			}
			return true
		},
		async getUserDiscountTakeEffect({
			state,
			commit,
			dispatch
		}) {
			const {
				data: dRes
			} = await getUserDiscountTakeEffect({
				status: 1
			})

			if (dRes.data) {
				dRes.data = dRes.data[0]
				commit('setDiscountNum', dRes.data.discount)
				commit('setDiscountTime', dRes.data.getTime)
				commit('setDiscountType', dRes.data.discountType)
				commit('setDiscountValidNumber', dRes.data.validNumber)
				commit('setDiscountId', dRes.data.discountUid)

				//设置多少秒后重新获取下优惠券信息

				// 优惠券的获取时间
				const couponStartTime = dayjs(dRes.data.getTime); // 假设获取时间为 "2023-11-02 08:00:00"
				// 有效小时数
				const validHours = dRes.data.validNumber; // 假设有效小时数为 24 小时
				// 计算到期时间
				const couponEndTime = couponStartTime.add(validHours, 'hour');
				// 获取到期时间的毫秒数
				const couponEndTimeMillis = couponEndTime.valueOf();
				// 获取当前时间的毫秒数
				const currentTimeMillis = dayjs().valueOf();
				// 计算倒计时剩余毫秒数
				const countdownMillis = couponEndTimeMillis - currentTimeMillis;
				if (state.countdownHandlId) {
					clearTimeout(state.countdownHandlId)
				}

				//大于0且小于setTimeout的最大值时
				if (countdownMillis > 0 && countdownMillis < 2147483647) {
					const handleId = setTimeout(() => {
						dispatch('getUserDiscountTakeEffect')
					}, countdownMillis)
					commit('setCountdownHandlId', handleId)
				}
			} else {
				commit('setDiscountNum', null)
				commit('setDiscountTime', '')
				commit('setDiscountValidNumber', 0)
				commit('setDiscountId', '')
			}
		},
		async getUserDiscountInfo({
			state,
			commit
		}) {
			const {
				data: dRes
			} = await getUserDiscountInfo()
			if (dRes.success) {
				commit('setDiscountList', {
					A: dRes.data.discount_one,
					B: dRes.data.discount_two,
					C: dRes.data.discount_three,
					D: dRes.data.discount_four,
					E: dRes.data.discount_five,
					ESHOP: dRes.data.discount_eshop,
					newUser400: dRes.data.discount_400,
					newUser10: dRes.data.discount_10,
					usedOk: dRes.data.taskInfo, //ABC优惠券已被使用过
					officalAccount: dRes.data.discount_wechat,
					yiyuan: dRes.data.discount_scl_1
				})
			}
			console.log(dRes, '======getUserDiscountInfo')
		},
		async getUserInfo({
			state,
			commit,
			dispatch
		}) {
			const {
				data: dRes
			} = await getUserInfoByCode(removeEmptyProperty({
				adType: state.adType
			}))

			if (dRes.code == 200) {
				console.log('----------------------------1---dc-----------------------')
				console.log(dRes, '=====dRes ---- isShowEconsultModal')
				const userInfo = Object.assign({}, dRes.data.user);
				const roles = Object.assign([], dRes.data.roles)

				userInfo.hasRecptionCasePermission = userInfo.roles?.includes("storesSell");

				uni.setStorageSync('balanceFlag', '1') //改变状态获取用户权益

				commit('setUserInfo', userInfo)
				commit('setUserChannel', dRes.data.userChannel)

				commit('setInviterId', dRes.data.inviter)
				commit('setPurchaseAndUsageCount', dRes.data.transactionCount)
				commit('setRoles', roles)
				commit('setCurrentGroup', dRes.data.groupInfo)
				commit('setIsVip', dRes.data.member)
				commit('setIsOldUser', !!dRes.data.oldUser)
				commit('setIsPaySclExamination', !!dRes.data.isPaySclExamination)
				commit('setNewUserCouponModalShow', !!dRes.data.newUser)
				commit('setNotUseLbYiyuan', dRes.data.sclOneGoods)

				commit('setCouponFirstMonthTime', dRes.data.discountTime)
				commit('setIsShowEconsultBlock', dRes.data.userRightsOnline)
				commit('setIsShowEconsultModal', dRes.data.giveEarTo)

				await dispatch('getUserDiscountInfo')
				await dispatch('getUserDiscountTakeEffect')
				await dispatch('getIsMember')
			} else {
				uni.showToast({
					title: dRes.message
				})
			}

		},
		/**
		 * 会员
		 */
		async getIsMember({commit}){
            const res = await isUserMember()
			if (res.data.success && res.data.data) {
				commit('setMember', {
					...res.data.data,
					memberEndTimeStr: res.data.data.memberEndTime ? dayjs(res.data.data.memberEndTime, 'YYYY-MM-DD HH:mm:ss').format('YYYY年M月D日') : ''
				})
			}
		}
	}
}